package com.authine.cloudpivot.ext.applicationservice;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.domain.dto.base.Ids;
import com.authine.cloudpivot.ext.dto.goods.VendorGoodsEntity;
import com.authine.cloudpivot.ext.dto.system.OrganizationDto;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.enums.ReviewStatusEnum;
import com.authine.cloudpivot.ext.enums.goods.GoodsType;
import com.authine.cloudpivot.ext.enums.report.ReportType;
import com.authine.cloudpivot.ext.service.GoodsService;
import com.authine.cloudpivot.ext.service.impl.GoodsServiceImpl;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.cloudpivot.ext.utils.boQuery.BoQueryUtils;
import com.authine.cloudpivot.ext.utils.system.OrgUtils;
import com.authine.cloudpivot.ext.utils.system.ReportUtils;
import com.authine.cloudpivot.ext.utils.system.SessionUser;
import com.authine.cloudpivot.metadata.design.dto.clientobject.domainmodel.schema.BizSchema;
import com.authine.hermes.app.file.dto.clientobject.DownLoadDTO;
import com.authine.hermes.app.file.feign.FtpFeignServiceI;
import com.authine.hermes.app.launcher.cmd.CmdWrapper;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.domain.AttachmentFormat;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.gateway.appmeata.query.MetaQueryI;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.cmd.UpdateBOCmd;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.dto.errorcode.ErrorCodeEnum;
import com.authine.mvp.app.launcher.rpc.SaveOrUpdateBO;
import com.authine.mvp.app.launcher.utils.ExcelUtils;
import com.authine.mvp.app.launcher.utils.ModelRuntimeException;
import com.authine.mvp.app.launcher.utils.RedisUtil;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Path("GoodsesService")
@Slf4j
public class GoodsesService extends ApplicationService {

    GoodsService goodsService = GoodsServiceImpl.getInstance();

    @Path("updateGoodsesCore")
    @POST
    @Operation(summary = "更新服务-是否核心产品", tags = CUSTOM_SERVICE)
    public SingleResponse<Boolean> updateGoodsesCore(Ids dto) {
        log.info("================dto ={}", JSON.toJSONString(dto));
        dto.getIds().forEach(a -> updateGoodsesField(a, "core"));
        return SingleResponse.buildSuccess();
    }

    @Path("updateGoodsesSaled")
    @POST
    @Operation(summary = "更新服务-上下架", tags = CUSTOM_SERVICE)

    public SingleResponse<Boolean> updateGoodsesSaled(Ids dto) {
        log.info("================dto ={}", JSON.toJSONString(dto));
        dto.getIds().forEach(a -> updateGoodsesField(a, "saled"));
        return SingleResponse.buildSuccess();
    }

    @Path("updateGoodsesEnabled")
    @POST
    @Operation(summary = "更新服务-启禁用", tags = CUSTOM_SERVICE)

    public SingleResponse<Boolean> updateGoodsesEnabled(Ids dto) {
        log.info("================dto ={}", JSON.toJSONString(dto));
        dto.getIds().forEach(a -> updateGoodsesField(a, "enabled"));
        return SingleResponse.buildSuccess();
    }

    public SingleResponse<Boolean> updateGoodsesField(String id, String field) {

        Boolean flag = true;


        SingleResponse<BO> bo = BoServiceUtils.loadBo(id, false, ModelConst.T_GOODSES, false);
        if (bo.isSuccess()) {
            CmdWrapper cmdWrapper = new CmdWrapper();
            UpdateBOCmd updateBOCmd = new UpdateBOCmd();
            Map<String, Object> map = new HashMap();
            map.put("id", id);

            Integer val = Optional.ofNullable((Integer) bo.getData().getData().get(field)).orElse(0);

            map.put(field, val.intValue() == 1 ? false : true);

            log.info("================updateBi-map ={}", JSON.toJSONString(map));
            SingleResponse result = BoServiceUtils.updateMainBo(ModelConst.T_GOODSES, Collections.singletonList(map));


            if (!result.isSuccess()) {
                flag = false;
            }

        } else {
            flag = false;
        }


        return SingleResponse.of(flag);
    }



    @Path("manageGoodsSave")
    @POST
    @Operation(summary = "商品保存", tags = CUSTOM_SERVICE)
    public SingleResponse manageGoodsSave(SaveOrUpdateBO bo) {

        //todo 权限验证  平台用户不允许增加和编辑商品
        if (null == bo || StringUtils.isNull(bo.getActionName()) || bo.getData().isEmpty() || StringUtils.isNull(bo.getSchemaCode())) {
            return SingleResponse.buildFailure("-1", "参数错误");
        }


        Map<String, Object> data = bo.getData();

        SessionUser sessionUser = new SessionUser();


        SingleResponse<BO> boSingleResponse = SingleResponse.buildSuccess();
        String brand = (String) data.get("brand");
        String name = (String) data.get("name");
        String model = (String) data.get("model");
        String spec = (String) data.get("spec");
        String package_unit = (String) data.get("package_unit");
        String unit = (String) data.get("unit");
        List<VendorGoodsEntity> list = goodsService.queryEqualGoods(sessionUser.getCurrentOrgID(), name, brand, model, spec, unit, package_unit, null);


        if (list != null && !list.isEmpty()) {
            bo.setActionName("update");
        }

        if ("update".equals(bo.getActionName())) {
            if (CollectionUtil.isNotEmpty(list)) {

                VendorGoodsEntity oldGoods = list.get(0);
                data.put("id", oldGoods.getId());
                Map<String, Object> oldData = JSON.parseObject(JSON.toJSONString(oldGoods));

                //添加历史记录
                addHistory(data, oldData);

                //同步其他客户   1.库存不一致  2.金额不一致  3.图片变更  4.规格变更
                //接口暂未有,等后续接口提供
                syncInfo(data, oldData);

                //目前没有shop_version 这个字段, 固买新加的字段, 先这样写着
                if ("v2".equals(oldData.get("shop_version"))) {
                    ReviewStatusEnum review_status = ReviewStatusEnum.getEnum(Integer.valueOf(String.valueOf(oldData.get("review_status"))));
                    if (review_status == ReviewStatusEnum.REVIEW_CONSENT) {
                        data.put("mall_sales", false);
                        data.put("review_status", ReviewStatusEnum.UNDER_REVIEW.ordinal());
                    } else if (review_status == ReviewStatusEnum.REVIEW_DISAGREE) {
                        data.put("review_status", ReviewStatusEnum.UNDER_REVIEW.ordinal());
                    }
                }
            }

            boSingleResponse = BoServiceUtils.updateMainBo(ModelConst.T_GOODSES, data);


        } else {

            data.put("type", GoodsType.Mall.ordinal());
            //todo 判断当前用户组织属性是虚拟供应商  type  是虚拟供应商  -> GoodsType.Virtual(虚拟商品) else -> GoodsType.Mall(固买商城)
         /*   OrganizationDto orgByOrgId = OrgUtils.getOrgByOrgId(sessionUser.getCurrentOrgID());
           if (orgByOrgId.getVirtual()){
               data.put("type", GoodsType.Virtual.ordinal());
           }*/

            data.put("cord", false);
            data.put("mallSales", false);
            data.put("review_status", ReviewStatusEnum.UN_REVIEWED.ordinal());
            data.put("mall_featured", false);

            if (null != data.get("id")) {
                boSingleResponse = BoServiceUtils.updateMainBo(ModelConst.T_GOODSES, bo.getData());
            } else {
                boSingleResponse = BoServiceUtils.createBo(bo.getSchemaCode(), Collections.singletonList(bo.getData()));
            }


            //jira5231要求商品新建以及编辑后,对应的状态为审批中(执行商城商品添加)
            if (boSingleResponse.isSuccess() && "v2".equals(bo.getData().get("shop_version"))) {
                //todo
                log.info("jira5231要求商品新建以及编辑后,对应的状态为审批中(执行商城商品添加)  ");
            }

        }

        if (boSingleResponse.isSuccess()) {
            return SingleResponse.of(boSingleResponse.getData().getBizObjectId());
        }
        return boSingleResponse;
    }

    /**
     * 加入历史记录
     */
    private void addHistory(Map<String, Object> data, Map<String, Object> oldData) {
        MetaQueryI metaQueryI = ApplicationContextUtils.getBean(MetaQueryI.class);
        //获取商品表的元数据
        BizSchema goodsMeta = metaQueryI.getBizSchemaByModel(ModelConst.T_GOODSES);
        //判断元素是否相等
        if (BoUtils.boCompare(goodsMeta.getProperties(), data, oldData)) {
            return;
        }
        // 给历史记录表赋值

        goodsService.addGoodsHistory(new ArrayList<>(Collections.singletonList(oldData)));

    }


    /**
     * 同步其他客户   1.库存不一致  2.金额不一致  3.图片变更  4.规格变更
     *
     * @param now
     * @param old
     */
    private void syncInfo(Map<String, Object> now, Map<String, Object> old) {
        try {
            //库存不一致
            if (new BigDecimal(String.valueOf(now.get("stock"))).compareTo(new BigDecimal(String.valueOf(old.get("stock")))) != 0) {
                //todo
                log.info("\n................库存不一致..............");
            }

            //金额不一致
            if (new BigDecimal(String.valueOf(now.get("pretax_price"))).compareTo(new BigDecimal(String.valueOf(old.get("pretax_price")))) != 0) {
                //todo
                log.info("\n................金额不一致..............");
            }
            //图片变更
            if (!Utils.imageEquals(now.get("images"), old.get("images"))) {
                //todo
                log.info("\n................图片不一致..............");
            }
            //规格变更
            if (!String.valueOf(now.get("spec")).equals(old.get("spec"))) {
                //todo
                log.info("\n............... 规格变更不一致..............");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Path("testTransf")
    @POST
    @Operation(summary = "测试事务", tags = CUSTOM_SERVICE)
    public void testTransf(SaveOrUpdateBO bo) {
        TransactionTemplate transactionTemplate = ApplicationContextUtils.getBean(TransactionTemplate.class);

        log.info("transactionTemplate 是null :{}", null == transactionTemplate);

        String p1 = (String) bo.getData().get("p1");
        String p2 = (String) bo.getData().get("p2");
        String p3 = (String) bo.getData().get("p3");

        transactionTemplate.execute(status -> {

            JdbcTemplateUtils.builder(ModelConst.T_GOODS_PURCHASE)
                    .putFieldAndVal("description", p1)
                    .eq("id", "15962833816117248")
                    .update();


            JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_QUOTATION_GOODS)
                    .putFieldAndVal("description", p2)
                    .eq("id", "295298")
                    .update();


            return null;
        });
    }


    @Path("testRedis")
    @POST
    @Operation(summary = "testRedis", tags = CUSTOM_SERVICE)
    public void testRedis() {

        RedisUtil redisUtil = ApplicationContextUtils.getBean(RedisUtil.class);


        SelectorFormat selectorFormat = new SelectorFormat();

        selectorFormat.setType(1);
        selectorFormat.setId("123213");
        selectorFormat.setName("name");

        Map<Object, Object> build = MapBuilder.create(new HashMap<>()).put("name", "123123")
                .put("detail", selectorFormat)
                .build();

        String key = "gm_build";

        Boolean gm_build = redisUtil.set(key, build, 3600);

        log.info("==============gm_build= {}", gm_build);

        Object getValue = redisUtil.get(key);

        log.info("==============getValue   = {}", getValue);


        String key1 = "gm_build1";

        Boolean setKey1 = redisUtil.set(key1, JSON.toJSONString(build), 3600);

        log.info("==============setKey1= {}", setKey1);

        Object getValue1 = redisUtil.get(key1);


        log.info("==============getValue1= {}", getValue1);


        Object o = JSON.toJSON(getValue1);

        log.info("==============JSON.toJSON= {}", o);


    }


    @Path("exportGoodsManageReport")
    @POST
    @Operation(summary = "供应商商品管理-导出", tags = CUSTOM_SERVICE, description = "入参:{data:{ids:[],fileType:'pdf/xlsx'}}")
    public SingleResponse exportGoodsManageReport(SaveOrUpdateBO bo) {
        List<String> ids = (List<String>) bo.getData().get("ids");
        if (ObjectUtils.isEmpty(ids)) {
            return SingleResponse.buildFailure("-1", "请求参数ids不能为空");
        }
        String fileType = (String) bo.getData().get("fileType");
        ReportType reportType = ReportType.get(fileType);
        if (reportType == null) {
            return SingleResponse.buildFailure("-1", "请求参数fileType不能为空");
        }

        SingleResponse<BOList> singleResponse = BoQueryUtils.Builder(ModelConst.T_GOODSES)
                .condition()
                .in("id", ids)
                .End().listBO();
        if (!singleResponse.isSuccess()) {
            return singleResponse;
        }
        List<Map<String, Object>> data = singleResponse.getData().getData();

        if (data.isEmpty()) {
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }

        String exportField = "{\"id\":\"id\",\"catalog\":\"catalog\",\"unit\":\"unit\",\"packageNum\":\"package_num\",\"packageUnit\":\"package_unit\",\"delivery\":\"delivery\",\"minOrder\":\"minOrder\",\"pretaxPrice\":\"pretax_price\",\"price\":\"price\",\"taxRate\":\"tax_rate\",\"stock\":\"stock\",\"orgFullname\":\"org_fullname\",\"time\":\"time\",\"expiry\":\"expiry\",\"saled\":\"saled\",\"enabled\":\"enabled\",\"name\":\"name\",\"brand\":\"brand\",\"model\":\"model\",\"spec\":\"spec\"}";
        JSONObject exportJson = JSON.parseObject(exportField);
        List<Map<String, Object>> fileData = data.stream().map(m -> {
            Map<String, Object> mf = new HashMap<>();
            for (String key : exportJson.keySet()) {
                mf.put(exportJson.getString(key), m.get(key));
            }
            return mf;
        }).collect(Collectors.toList());

        ReportUtils.exportReport("goods/goods_manage_report.jrxml", reportType.getId(), fileData);

        return SingleResponse.buildSuccess();
    }

    @Path("exportCoreGoodsReport")
    @POST
    @Operation(summary = "核心商品库-导出", tags = CUSTOM_SERVICE, description = "入参:{data:{ids:[],fileType:'pdf/xlsx'}}")
    public SingleResponse exportCoreGoodsReport(SaveOrUpdateBO bo) {
        List<String> ids = (List<String>) bo.getData().get("ids");
        if (ObjectUtils.isEmpty(ids)) {
            return SingleResponse.buildFailure("-1", "请求参数ids不能为空");
        }
        String fileType = (String) bo.getData().get("fileType");
        ReportType reportType = ReportType.get(fileType);
        if (reportType == null) {
            return SingleResponse.buildFailure("-1", "请求参数fileType不能为空");
        }

        SingleResponse<BOList> singleResponse = BoQueryUtils.Builder(ModelConst.T_GOODSES)
                .condition()
                .in("id", ids)
                .End().listBO();
        if (!singleResponse.isSuccess()) {
            return singleResponse;
        }
        List<Map<String, Object>> data = singleResponse.getData().getData();

        if (data.isEmpty()) {
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }
        if (log.isDebugEnabled()) {
            log.debug("======================获取报表参数:list={}", JSON.toJSONString(data));
        }
        data.forEach(m -> {
            SelectorFormat selectorFormat = Utils.toSelectorFormat(m.get("vendor_id"));
            if (selectorFormat != null) {
                m.put("vendor_id", selectorFormat.getId());
            }
        });

        String exportField = "{\"id\":\"id\",\"vendorId\":\"vendor_id\",\"catalog\":\"catalog\",\"name\":\"name\",\"brand\":\"brand\",\"model\":\"model\",\"spec\":\"spec\",\"unit\":\"unit\",\"packageNum\":\"package_num\",\"package_unit\":\"package_unit\",\"minOrder\":\"min_order\",\"delivery\":\"delivery\",\"pretaxPrice\":\"pretax_price\",\"taxRate\":\"tax_rate\",\"stock\":\"stock\",\"time\":\"createdTime\",\"expiry\":\"expiry\",\"createBy\":\"createdBy\",\"price\":\"price\"}";
        JSONObject exportJson = JSON.parseObject(exportField);
        List<Map<String, Object>> fileData = data.stream().map(m -> {
            Map<String, Object> mf = new HashMap<>();
            for (String key : exportJson.keySet()) {
                mf.put(exportJson.getString(key), m.get(key));
            }
            return mf;
        }).collect(Collectors.toList());

        if (log.isDebugEnabled()) {
            log.debug("======================报表导出参数:reportType={},fileData={}", reportType.getId(), JSON.toJSONString(fileData));
        }
        ReportUtils.exportReport("goods/core_goods_report.jrxml", reportType.getId(), fileData);

        return SingleResponse.buildSuccess();
    }


    @Path("vendorGoodsUpload")
    @POST
    @Operation(summary = "供应商商品管理-物品导入", tags = CUSTOM_SERVICE)
    public SingleResponse vendorGoodsUpload(SaveOrUpdateBO bo) {

        String refId = (String) bo.getData().get("refId");
        log.info("入参 :{}", refId);
        if (StringUtils.isNull(refId)) {
            throw new ModelRuntimeException(ErrorCodeEnum.BIZ_PARAMS_ERR, "文件id不存在");
        }
        FtpFeignServiceI ftpFeignServiceI = ApplicationContextUtils.getBean(FtpFeignServiceI.class);
        SingleResponse<DownLoadDTO> response = ftpFeignServiceI.downloadBytes(refId);

        if (!response.isSuccess()) {
            throw BoUtils.bizException("获取文件失败".concat(response.getErrMessage()));
        }
        if (response.getData() == null) {
            throw BoUtils.bizException("文件流数据为空");
        }
        InputStream inputStream = new ByteArrayInputStream(response.getData().getImageBytes());
        if (inputStream == null) {
            throw BoUtils.bizException("获取文件流数据为空");
        }

        List<List<String>> dataList;
        try {

            dataList = ExcelUtils.readXlsxFirstSheet(inputStream);
        } catch (IOException var10) {
            log.error("preValidateImport========ByteArrayInputStream error", var10);
            throw new BizException("导入文件上传失败");
        }

        if (dataList.isEmpty() || dataList.size() == 1) {
            return SingleResponse.buildFailure("-1", "数据不能为空");
        }
        //对应每列的字段
        String[] filed = new String[]{"brand", "name", "model", "spec", "catalog", "unit", "package_num", "package_unit", "min_order", "tax_rate", "pretax_price", "delivery_place", "period_alidity", "stock", "delivery", "enabled", "sku", "bar_code", "golden_tax", "unspsc", "description", "technical", "packaging", "place", "length", "width", "height", "weight", "memo", "safe_stock", "warranty", "images", "stock_delivery", "delivery_claim", "godds_detail_images"};

        List<Map<String, String>> list = dataList.subList(1, dataList.size()).stream().map(strList -> {
            Map<String, String> m = new HashMap<>();
            for (int i = 0; i < strList.size(); i++) {
                m.put(filed[i], strList.get(i));
            }
            return m;
        }).collect(Collectors.toList());

        return checkUpload(list);

    }

    private SingleResponse checkUpload(List<Map<String, String>> list) {
        Map<String, String> map;
        Map<String, Object> checkMap;
        List<Map<String, Object>> checkList = new ArrayList<>();


        Map<String, String> brandMap = getBrandMap();
        Map<String, String> catalogMap = getCatalogMap();
        Map<String, String> unitMap = getUnitMap();
        Map<String, String> taxRateMap = getTaxRateMap();

        int row = 0;
        for (int i = 0; i < list.size(); i++) {
            ++row;
            map = list.get(i);
            String brand = Optional.ofNullable(map.get("brand")).orElse("");
            String name = Optional.ofNullable(map.get("name")).orElse("");
            String model = Optional.ofNullable(map.get("model")).orElse("");
            String spec = Optional.ofNullable(map.get("spec")).orElse("");

            if (StringUtils.isBlank(brand) && StringUtils.isBlank(name) && StringUtils.isBlank(model) && StringUtils.isBlank(spec)) {
                continue;
            }
            if (brand.length() > 200) {
                return buildFailure("品牌", row);
            }
            if (name.length() > 200) {
                return buildFailure("商品名称", row);
            }
            if (model.length() > 200) {
                return buildFailure("型号", row);
            }
            if (spec.length() > 200) {
                return buildFailure("规格", row);
            }

            String min_order = map.get("min_order");

            if (StringUtils.isNotBlank(min_order)) {
                if (!RegexUtils.check(RegexUtils.Type.IS_NUMBER, min_order)) {
                    return SingleResponse.buildFailure("-1", String.format("第 %s 行的最小起订量只能填写阿拉伯数字！", row));
                }

            }
            String delivery_place = map.get("delivery_place");


            if (delivery_place.length() > 200) {
                return buildFailure("发货地", row);
            }
            //图片导入数据类型
            String images = map.get("images");
            List<AttachmentFormat> imagesAf = new ArrayList<>();
            if (images != null) {
                imagesAf = Stream.of(images.split(",")).map(str -> {
                    AttachmentFormat af = new AttachmentFormat();
                    af.setId(str);
                    af.setFileSize(1d);
                    af.setName("1");
                    af.setMimeType("*");

                    return af;
                }).collect(Collectors.toList());
            }

            String package_num = map.get("package_num");

            if (StringUtils.isNotBlank(package_num)) {
                if (!RegexUtils.check(RegexUtils.Type.IS_NUMBER, package_num)) {
                    return SingleResponse.buildFailure("-1", String.format("第 %s 行的包装数量只能填写阿拉伯数字！", row));
                }
            }
            Double taxRate = MapUtil.getDouble(map, "tax_rate");
            if (taxRate == null) {
                return SingleResponse.buildFailure("-1", String.format("第 %s 行的税率不正确", row));
            }
            Double pretaxPrice = MapUtil.getDouble(map, "pretax_price");
            if (taxRate == null) {
                return SingleResponse.buildFailure("-1", String.format("第 %s 行的税前价不正确", row));
            }
            BigDecimal mul = BigDecimalUtils.mul(new BigDecimal(pretaxPrice), new BigDecimal(taxRate));
            BigDecimal price = BigDecimalUtils.add(mul, new BigDecimal(pretaxPrice));

            String enabled = map.get("enabled");
            boolean enabledval = !RegexUtils.notNull(enabled) || "启用".equals(enabled);
            if (!enabledval && !"禁用".equals(enabled)) {
                return SingleResponse.buildFailure("-1", String.format("第 %s 行的启禁用格式不正确, 只能为启用, 禁用或者为空", row));
            }

            if (!RegexUtils.check(RegexUtils.Type.IS_NUMBER, map.get("delivery"))) {
                return SingleResponse.buildFailure("-1", String.format("第 %s 行的无库存货期只能填写阿拉伯数字！", row));
            }
            Integer delivery = MapUtil.getInt(map, "delivery");
            if (delivery == null) {
                return SingleResponse.buildFailure("-1", String.format("第 %s 行的无库存货期不能为空", row));
            }
            if (delivery <= 0) {
                return SingleResponse.buildFailure("-1", String.format("第 %s 行的无库存货期必须大于0", row));
            }


            Double length = MapUtil.getDouble(map, "length");
            Double width = MapUtil.getDouble(map, "width");
            Double height = MapUtil.getDouble(map, "height");
            Double weight = MapUtil.getDouble(map, "weight");


            checkMap = new HashMap<>();

            checkList.add(checkMap);

            checkMap.putAll(map);
            checkMap.put("price", price);
            checkMap.put("brand_id", brandMap.get(brand));
            checkMap.put("catalog_id", catalogMap.get(brand));
            checkMap.put("unit_id", unitMap.get(brand));
            checkMap.put("package_unit_id", unitMap.get(brand));
            checkMap.put("tax_rate_id", taxRateMap.get(brand));
            checkMap.put("length", length);
            checkMap.put("width", width);
            checkMap.put("height", height);
            checkMap.put("weight", weight);
            checkMap.put("images", imagesAf);


        }

        return SingleResponse.of(checkList);
    }


    private Map<String, String> getBrandMap() {
        List<Map<String, Object>> list = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_GOODS_BRAND)
                .selectField("DISTINCT(name_cn) as name,id")
                .queryForList();

        Map<String, String> collect = list.stream().collect(Collectors.toMap(a -> String.valueOf(a.get("name")), a -> String.valueOf(a.get("id")), (k1, k2) -> k1));
        return collect;

    }

    private Map<String, String> getCatalogMap() {
        List<Map<String, Object>> list = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_GOODS_CATALOG)
                .selectField("DISTINCT(name) as name,id")
                .queryForList();

        Map<String, String> collect = list.stream().collect(Collectors.toMap(a -> String.valueOf(a.get("name")), a -> String.valueOf(a.get("id")), (k1, k2) -> k1));
        return collect;

    }

    private Map<String, String> getUnitMap() {
        List<Map<String, Object>> list = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_GOODS_UNIT)
                .selectField("DISTINCT(name) as name,id")
                .queryForList();

        Map<String, String> collect = list.stream().collect(Collectors.toMap(a -> String.valueOf(a.get("name")), a -> String.valueOf(a.get("id")), (k1, k2) -> k1));
        return collect;
    }

    private Map<String, String> getTaxRateMap() {
        List<Map<String, Object>> list = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_GOODS_TAX_RATE)
                .selectField("DISTINCT(percents) as name,id")
                .queryForList();

        Map<String, String> collect = list.stream().collect(Collectors.toMap(a -> String.valueOf(a.get("name")), a -> String.valueOf(a.get("id")), (k1, k2) -> k1));
        return collect;
    }


    private SingleResponse buildFailure(String msg, int row) {

        return SingleResponse.buildFailure("-1", String.format("第 %s 行的 %s 内容不能大于200！", row, msg));
    }

    @Path("vendorGoodsUploadSubmit")
    @POST
    @Operation(summary = "供应商商品管理-物品导入提交", tags = CUSTOM_SERVICE)
    public SingleResponse vendorGoodsUploadSubmit(BOList listBo) {
        List<Map<String, Object>> list = listBo.getData();
        if (list.isEmpty()) {
            return SingleResponse.buildFailure("-1", "数据不能未空");
        }

        //可以换成调用  manageGoodsSave
        SingleResponse<BO> bo = BoServiceUtils.createBo(listBo.getSchemaCode(), list);

        if (bo.isSuccess()) {
            return SingleResponse.buildSuccess();
        } else {
            return bo;
        }
    }

}
